<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
	xmlns="http://www.w3.org/2000/svg"
	xmlns:svg="http://www.w3.org/2000/svg"
	xmlns:dg="livcos.org/ns/doc/diagram"
	xmlns:xlink="http://www.w3.org/1999/xlink"
	xmlns:xs="http://www.w3.org/2001/XMLSchema"
	xmlns:f="livcos.org/ns/xslt/function"
	exclude-result-prefixes="dg f xs svg xlink">
	
	<xsl:import href="base.xsl"/>
	
	<xsl:variable name="contentBaseUris" select="resolve-uri('ns')"/>
	<xsl:variable name="defaultDetailsView"/>
	
	<xsl:template match="dg:*" mode="prep">
		<xsl:sequence select="."/>
	</xsl:template>
	
	<xsl:template match="dg:box" mode="prep">
		<xsl:variable name="entity" select="f:entity(@ref)"/>
		<xsl:choose>
			<xsl:when test="(@ref != '') and $entity">
				<xsl:variable name="detailsView" select="(@details-view, ../@details-view, $defaultDetailsView)[1]"/>
				<xsl:variable name="nsViews" select="f:find-objs-for-namespaces($entity, $contentBaseUris, 'view')"/>
				<xsl:variable name="b" select="f:transform('', $entity, ('detailsView', $detailsView), $nsViews)/*"/>
				<xsl:copy>
					<xsl:sequence select="@*"/>
					<xsl:sequence select="$b/@*"/>
					<xsl:sequence select="$b/svg:*"/>
				</xsl:copy>
				<xsl:apply-templates select="$b/dg:*" mode="prep">
					<xsl:with-param name="boxId" select="@id"/>
				</xsl:apply-templates>
			</xsl:when>
			<xsl:otherwise>
				<xsl:variable name="label" 
					select="if (@ref != '') then concat('Entity ', @ref, ' not found!') else '-- entity --'"/>
				<xsl:variable name="w" select="string-length($label) * 7 + 10"/>
				<xsl:variable name="h" select="30"/>
				<xsl:variable name="c" select="$w div 2, $h div 2"/>
				<dg:box width="{$w}" height="{$h}">
					<xsl:sequence select="@*"/>
					<g fill="#FF9999">
						<rect stroke="#001122" x="0" y="0" width="{$w}" height="{$h}" rx="1" ry="1"/>
						<text x="{$c[1]}" y="{$c[2] + 3}" fill="black" style="text-anchor: middle; font-size: 12px">
							<xsl:value-of select="$label"/>
						</text>
					</g>
				</dg:box>
			</xsl:otherwise>
		</xsl:choose>
	</xsl:template>
	
	<xsl:template match="dg:box[svg:*]" mode="prep">
		<xsl:copy>
			<xsl:sequence select="@*"/>
			<xsl:sequence select="svg:*"/>
		</xsl:copy>
		<xsl:apply-templates select="dg:*" mode="prep">
			<xsl:with-param name="boxId" select="@id"/>
		</xsl:apply-templates>
	</xsl:template>
	
	<xsl:template match="dg:path" mode="prep">
		<xsl:copy>
			<xsl:sequence select="@*"/>
			<xsl:attribute name="ref" select="f:abs-ref(@ref)"/>
			<xsl:sequence select="*"/>
		</xsl:copy>
	</xsl:template>
	
	<xsl:template match="dg:connect" mode="prep">
		<xsl:param name="boxId"/>
		<xsl:copy>
			<xsl:sequence select="@*"/>
			<xsl:if test="not(@start)">
				<xsl:attribute name="start" select="$boxId"/>
			</xsl:if>
			<xsl:sequence select="*"/>
		</xsl:copy>
	</xsl:template>
	
</xsl:stylesheet>